package com.springboot.framework.controller;

import com.springboot.framework.controller.request.CouponsInsertBean;
import com.springboot.framework.controller.request.CouponsUpdateBean;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.CouponsModel;
import com.springboot.framework.service.CouponsService;
import com.springboot.framework.utils.ResponseVoUtil;
import com.springboot.framework.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 管理员发券
 * @author SWF
 * @date 2019/6/20 10:35
 **/
@Api(description = "【管理员】coupons发券")
@RestController
@RequestMapping("/admin/coupons")
public class AdminCouponsController {

    @Resource
    private CouponsService couponsService;

    @ApiOperation(value = "新增优惠券",notes = "新增优惠券")
    @PostMapping("/insert")
    public ResponseVO<CouponsModel> insert(@RequestBody @Valid CouponsInsertBean bean, BindingResult bindingResult, HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
        }
        CouponsModel couponsModel = new CouponsModel();
        BeanUtils.copyProperties(bean,couponsModel);
        couponsModel.setEffectiveDuration((short) (bean.getEffectiveDuration()*24));
        couponsModel = couponsService.insert(couponsModel);
        return ResponseVoUtil.success(couponsModel);
    }

    @ApiOperation(value = "查看发放的优惠券列表",notes = "查看发放的优惠券列表")
    @GetMapping("/list")
    public ResponseVO<List<CouponsModel>> list(HttpServletRequest request){
        List<CouponsModel> couponsModelList = couponsService.list();
        return ResponseVoUtil.success(couponsModelList);
    }

    @ApiOperation(value = "更新优惠券",notes = "更新优惠券")
    @PostMapping("/update")
    public ResponseVO<CouponsModel> update(@RequestBody @Valid CouponsUpdateBean bean, BindingResult bindingResult, HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
        }
        CouponsModel couponsModel = new CouponsModel();
        BeanUtils.copyProperties(bean,couponsModel);
        couponsModel.setEffectiveDuration((short) (bean.getEffectiveDuration()*24));
        couponsModel = couponsService.update(couponsModel);
        return ResponseVoUtil.success(couponsModel);
    }


    @ApiOperation(value = "更新优惠券",notes = "更新优惠券")
    @DeleteMapping("/delete")
    public ResponseVO<CouponsModel> update(@RequestParam Integer couponsId, HttpServletRequest request){
        couponsService.delete(couponsId);
        return ResponseVoUtil.success();
    }


}
